package com.yunke.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunke.common.result.YunkeResult;
import com.yunke.dto.service.YunkeServiceBookDto;
import com.yunke.dto.service.YunkeServicePublishDto;
import com.yunke.service.YunkeServiceService;
import com.yunke.vo.service.YunkeServiceVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 服务交易Controller
 * 
 * @author yunke
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/service")
@Tag(name = "服务交易", description = "服务交易相关接口")
public class YunkeServiceController {

    @Autowired
    private YunkeServiceService serviceService;

    /**
     * 获取服务分类列表
     */
    @GetMapping("/category")
    @Operation(summary = "获取服务分类列表", description = "获取系统支持的所有服务分类")
    public YunkeResult<List<YunkeServiceVo.CategoryInfo>> getServiceCategory() {
        try {
            log.info("获取服务分类列表");
            List<YunkeServiceVo.CategoryInfo> categoryList = serviceService.getServiceCategory();
            return YunkeResult.success(categoryList);
        } catch (Exception e) {
            log.error("获取服务分类列表失败", e);
            return YunkeResult.error("获取服务分类列表失败");
        }
    }

    /**
     * 发布服务
     */
    @PostMapping("/publish")
    @Operation(summary = "发布服务", description = "用户发布新的服务信息")
    public YunkeResult<Long> publishService(@Valid @RequestBody YunkeServicePublishDto publishDto) {
        try {
            log.info("发布服务: title={}", publishDto.getTitle());
            Long serviceId = serviceService.publishService(publishDto);
            return YunkeResult.success(serviceId, "服务发布成功");
        } catch (Exception e) {
            log.error("发布服务失败", e);
            return YunkeResult.error("发布服务失败：" + e.getMessage());
        }
    }

    /**
     * 获取服务列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取服务列表", description = "分页获取服务列表，支持分类、类型、关键词筛选和多种排序")
    public YunkeResult<Page<YunkeServiceVo>> getServiceList(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "服务分类ID") @RequestParam(required = false) Long categoryId,
            @Parameter(description = "服务类型：1-线上服务 2-线下服务 3-上门服务") @RequestParam(required = false) Integer serviceType,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "排序类型：1-综合排序 2-价格升序 3-价格降序 4-评分排序 5-距离排序") @RequestParam(defaultValue = "1") Integer sortType,
            @Parameter(description = "经度（距离排序时需要）") @RequestParam(required = false) Double longitude,
            @Parameter(description = "纬度（距离排序时需要）") @RequestParam(required = false) Double latitude) {
        try {
            log.info("获取服务列表: current={}, size={}, categoryId={}, serviceType={}, keyword={}", 
                    current, size, categoryId, serviceType, keyword);
            Page<YunkeServiceVo> result = serviceService.getServiceList(current, size, categoryId, serviceType, 
                    keyword, sortType, longitude, latitude);
            return YunkeResult.success(result);
        } catch (Exception e) {
            log.error("获取服务列表失败", e);
            return YunkeResult.error("获取服务列表失败");
        }
    }

    /**
     * 获取服务详情
     */
    @GetMapping("/detail/{serviceId}")
    @Operation(summary = "获取服务详情", description = "根据服务ID获取服务详细信息")
    public YunkeResult<YunkeServiceVo> getServiceDetail(
            @Parameter(description = "服务ID", example = "1") @PathVariable Long serviceId) {
        try {
            log.info("获取服务详情: serviceId={}", serviceId);
            YunkeServiceVo serviceVo = serviceService.getServiceDetail(serviceId);
            return YunkeResult.success(serviceVo);
        } catch (Exception e) {
            log.error("获取服务详情失败", e);
            return YunkeResult.error("获取服务详情失败：" + e.getMessage());
        }
    }

    /**
     * 预订服务
     */
    @PostMapping("/book")
    @Operation(summary = "预订服务", description = "用户预订服务，创建服务订单")
    public YunkeResult<Long> bookService(@Valid @RequestBody YunkeServiceBookDto bookDto) {
        try {
            log.info("预订服务: serviceId={}", bookDto.getServiceId());
            Long orderId = serviceService.bookService(bookDto);
            return YunkeResult.success(orderId, "预订成功");
        } catch (Exception e) {
            log.error("预订服务失败", e);
            return YunkeResult.error("预订失败：" + e.getMessage());
        }
    }

    /**
     * 订单支付
     */
    @PostMapping("/pay/{orderId}")
    @Operation(summary = "订单支付", description = "支付服务订单")
    public YunkeResult<Object> payServiceOrder(
            @Parameter(description = "订单ID", example = "1") @PathVariable Long orderId,
            @Parameter(description = "支付方式：1-余额支付 2-微信支付 3-支付宝支付", example = "1") @RequestParam Integer payMethod,
            @Parameter(description = "支付密码（余额支付时需要）") @RequestParam(required = false) String payPassword) {
        try {
            log.info("订单支付: orderId={}, payMethod={}", orderId, payMethod);
            Object result = serviceService.payServiceOrder(orderId, payMethod, payPassword);
            return YunkeResult.success(result, "支付成功");
        } catch (Exception e) {
            log.error("订单支付失败", e);
            return YunkeResult.error("支付失败：" + e.getMessage());
        }
    }

    /**
     * 确认服务订单
     */
    @PostMapping("/confirm/{orderId}")
    @Operation(summary = "确认服务订单", description = "服务提供者确认接单")
    public YunkeResult<Boolean> confirmServiceOrder(
            @Parameter(description = "订单ID", example = "1") @PathVariable Long orderId) {
        try {
            log.info("确认服务订单: orderId={}", orderId);
            boolean result = serviceService.confirmServiceOrder(orderId);
            return YunkeResult.success(result, "确认成功");
        } catch (Exception e) {
            log.error("确认服务订单失败", e);
            return YunkeResult.error("确认失败：" + e.getMessage());
        }
    }

    /**
     * 完成服务订单
     */
    @PostMapping("/complete/{orderId}")
    @Operation(summary = "完成服务订单", description = "标记服务订单为已完成")
    public YunkeResult<Boolean> completeServiceOrder(
            @Parameter(description = "订单ID", example = "1") @PathVariable Long orderId) {
        try {
            log.info("完成服务订单: orderId={}", orderId);
            boolean result = serviceService.completeServiceOrder(orderId);
            return YunkeResult.success(result, "完成成功");
        } catch (Exception e) {
            log.error("完成服务订单失败", e);
            return YunkeResult.error("完成失败：" + e.getMessage());
        }
    }

    /**
     * 我发布的服务
     */
    @GetMapping("/myPublished")
    @Operation(summary = "我发布的服务", description = "获取当前用户发布的服务列表")
    public YunkeResult<Page<YunkeServiceVo>> getMyPublishedService(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "服务状态：1-发布中 2-暂停接单 3-已下架") @RequestParam(required = false) Integer status) {
        try {
            log.info("获取我发布的服务: current={}, size={}, status={}", current, size, status);
            Page<YunkeServiceVo> result = serviceService.getMyPublishedService(current, size, status);
            return YunkeResult.success(result);
        } catch (Exception e) {
            log.error("获取我发布的服务失败", e);
            return YunkeResult.error("获取失败");
        }
    }

    /**
     * 我的服务订单
     */
    @GetMapping("/myOrder")
    @Operation(summary = "我的服务订单", description = "获取当前用户的服务订单列表")
    public YunkeResult<Page<Object>> getMyServiceOrder(
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "订单类型：1-我购买的 2-我提供的", example = "1") @RequestParam Integer orderType,
            @Parameter(description = "订单状态") @RequestParam(required = false) Integer status) {
        try {
            log.info("获取我的服务订单: current={}, size={}, orderType={}, status={}", current, size, orderType, status);
            Page<Object> result = serviceService.getMyServiceOrder(current, size, orderType, status);
            return YunkeResult.success(result);
        } catch (Exception e) {
            log.error("获取我的服务订单失败", e);
            return YunkeResult.error("获取失败");
        }
    }

    /**
     * 评价服务
     */
    @PostMapping("/review/{orderId}")
    @Operation(summary = "评价服务", description = "对已完成的服务进行评价")
    public YunkeResult<Boolean> reviewService(
            @Parameter(description = "订单ID", example = "1") @PathVariable Long orderId,
            @Parameter(description = "综合评分", example = "4.5") @RequestParam Double rating,
            @Parameter(description = "服务态度评分", example = "4.5") @RequestParam(required = false) Double serviceRating,
            @Parameter(description = "专业能力评分", example = "4.5") @RequestParam(required = false) Double skillRating,
            @Parameter(description = "时效性评分", example = "4.5") @RequestParam(required = false) Double timeRating,
            @Parameter(description = "性价比评分", example = "4.5") @RequestParam(required = false) Double valueRating,
            @Parameter(description = "评价内容") @RequestParam(required = false) String content,
            @Parameter(description = "评价图片，多张用逗号分隔") @RequestParam(required = false) String images,
            @Parameter(description = "是否匿名评价") @RequestParam(defaultValue = "false") Boolean isAnonymous,
            @Parameter(description = "评价标签，多个用逗号分隔") @RequestParam(required = false) String tags) {
        try {
            log.info("评价服务: orderId={}, rating={}", orderId, rating);
            boolean result = serviceService.reviewService(orderId, rating, serviceRating, skillRating, 
                    timeRating, valueRating, content, images, isAnonymous, tags);
            return YunkeResult.success(result, "评价成功");
        } catch (Exception e) {
            log.error("评价服务失败", e);
            return YunkeResult.error("评价失败：" + e.getMessage());
        }
    }

    /**
     * 获取服务评价列表
     */
    @GetMapping("/reviewList/{serviceId}")
    @Operation(summary = "获取服务评价列表", description = "获取指定服务的评价列表")
    public YunkeResult<Page<Object>> getServiceReviewList(
            @Parameter(description = "服务ID", example = "1") @PathVariable Long serviceId,
            @Parameter(description = "当前页码", example = "1") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "评分筛选：0-全部 1-好评 2-中评 3-差评") @RequestParam(defaultValue = "0") Integer ratingFilter) {
        try {
            log.info("获取服务评价列表: serviceId={}, current={}, size={}, ratingFilter={}", 
                    serviceId, current, size, ratingFilter);
            Page<Object> result = serviceService.getServiceReviewList(serviceId, current, size, ratingFilter);
            return YunkeResult.success(result);
        } catch (Exception e) {
            log.error("获取服务评价列表失败", e);
            return YunkeResult.error("获取失败");
        }
    }

    /**
     * 取消服务订单
     */
    @PostMapping("/cancel/{orderId}")
    @Operation(summary = "取消服务订单", description = "取消服务订单")
    public YunkeResult<Boolean> cancelServiceOrder(
            @Parameter(description = "订单ID", example = "1") @PathVariable Long orderId,
            @Parameter(description = "取消原因") @RequestParam String cancelReason) {
        try {
            log.info("取消服务订单: orderId={}, cancelReason={}", orderId, cancelReason);
            boolean result = serviceService.cancelServiceOrder(orderId, cancelReason);
            return YunkeResult.success(result, "取消成功");
        } catch (Exception e) {
            log.error("取消服务订单失败", e);
            return YunkeResult.error("取消失败：" + e.getMessage());
        }
    }

    /**
     * 申请退款
     */
    @PostMapping("/refund/{orderId}")
    @Operation(summary = "申请退款", description = "申请服务订单退款")
    public YunkeResult<Boolean> applyRefund(
            @Parameter(description = "订单ID", example = "1") @PathVariable Long orderId,
            @Parameter(description = "退款原因") @RequestParam String refundReason) {
        try {
            log.info("申请退款: orderId={}, refundReason={}", orderId, refundReason);
            boolean result = serviceService.applyRefund(orderId, refundReason);
            return YunkeResult.success(result, "申请成功");
        } catch (Exception e) {
            log.error("申请退款失败", e);
            return YunkeResult.error("申请失败：" + e.getMessage());
        }
    }
} 